<html>

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>首页</title>
</head>

<style>
	.operation {
		margin: 20px auto;
	}

	.operation>button {
		margin: 20px;
	}

	.form>p {
		width: 300px;
		display: flex;
		justify-content: space-between;
	}
</style>

<body>
	<div>
		<img src="../public/1.jpg" alt="">
		<p><%= msg %></p>
		<p>欢迎进行数据操作</p>

		<div class="form">
			<p>id:<input id="id" type="number" value="2"></p>
			<p>name:<input id="name" type="text"></p>
			<p>desc:<input id="desc" type="text"></p>
			<p>file:<input id="file" type="text"></p>
			<p>view:<input id="view" type="text"></p>
			<p>isPulish:<input id="isp" type="text"></p>
		</div>

		<div class="operation">
			<button onclick="getData()">get</button>
			<button onclick="createData()">post</button>
			<button onclick="updataData()">update</button>
			<button onclick="deleteData()">delete</button>
		</div>

		<div>信息：</div>
		<div id="info">

		</div>

		<hr>

		<div>原数据：</div>
		<div id="content">

		</div>
	</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dexie/2.0.4/dexie.min.js"
	integrity="sha256-ubffRsoh9QK5xJC/u3s3drtGFBZUHBm9bHFRzYvtkJI=" crossorigin="anonymous"></script>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>

<script type="text/javascript">
	var baseURL = 'http://localhost:8870'
	var suffixURL = '/test/db'

	// 新建indexedDB
	// var db;
	// var request = window.indexedDB.open('frontDB', 3);

	const db = new Dexie("frontDatabase");
	db.version(1).stores({
		friends: "++id,name,age"
	});
	db.version(1).stores({
		request: "++id,url,type,attr"
	});

	// db.transaction('rw', db.friends, async () => {

	// 	// Make sure we have something in DB:
	// 	if ((await db.friends.where({
	// 			name: 'Josephine'
	// 		}).count()) === 0) {
	// 		const id = await db.friends.add({
	// 			name: "Josephine",
	// 			age: 21
	// 		});
	// 		alert(`Addded friend with id ${id}`);
	// 	}

	// 	// Query:
	// 	const youngFriends = await db.friends.where("age").below(25).toArray();

	// 	// Show result:
	// 	alert("My young friends: " + JSON.stringify(youngFriends));

	// }).catch(e => {
	// 	alert(e.stack || e);
	// });


	// await new Promise(async (resolve) => {
	// await new Promise((resolve) => {
	// 	request.addEventListener('success', e => {
	// 		console.log("连接数据库成功");
	// 		db = e.target.result;
	// 		resolve()
	// 	});

	// })


	// request.addEventListener('upgradeneeded', e => {
	// 	const db = e.target.result;
	// 	if (!db.objectStoreNames.contains('Users')) {
	// 		const store = db.createObjectStore('Users', {
	// 			keyPath: 'id',
	// 			autoIncrement: false
	// 		});
	// 		console.log('创建对象仓库成功');
	// 	}

	// });

	// request.addEventListener('error', e => {
	// 	console.log("连接数据库失败");
	// });

	// add()

	// function add() {
	// 	var request = db.transaction(['Users'], 'readwrite')
	// 		.objectStore('Users')
	// 		.add({
	// 			id: 4,
	// 			name: '张三',
	// 			age: 24,
	// 			email: 'zhangsan@example.com'
	// 		});

	// 	request.onsuccess = function (event) {
	// 		console.log('数据写入成功');
	// 	};

	// 	request.onerror = function (event) {
	// 		console.error(event.target.error)
	// 		console.log('数据写入失败');
	// 	}
	// }





	// websocket
	const socket = io('ws://localhost:81/msg');
	socket.on('connect', function () {
		console.log('Connected');
		setInfo('server', 'Connected')
	});
	socket.on('exception', function (data) {
		console.log('exception', data);
	});
	socket.on('disconnect', function () {
		console.log('Disconnected');
		setInfo('server', 'Disconnected')
	});

	//監聽新訊息事件
	socket.on('newMessage', function (msg) {
		//顯示訊息 
		console.log(msg)
		setInfo('server', msg)
		// $('#messages').append($('<li>').text(msg));
		// window.scrollTo(0, document.body.scrollHeight);
	});

	//監聽新訊息事件
	socket.on('fromServerMsg', function (msg) {
		//顯示訊息 
		console.log(msg)
		setInfo('server', msg)
		// $('#messages').append($('<li>').text(msg));
		// window.scrollTo(0, document.body.scrollHeight);
	});



	function getData() {

		var id = $('#id').val()
		let msg = "I'm client."
		socket.emit('pushMessage', msg);
		setInfo('client', msg)

		sendRequest(suffixURL, 'GET', {
			id: id
		}).then(res => {
			alert('获取成功')
			changeDIV(res)
		})
	}

	function createData() {

		var name = $('#name').val()
		var desc = $('#desc').val()
		var file = $('#file').val()
		var view = $('#view').val()
		var isp = $('#isp').val()
		console.log(name)

		sendRequest(suffixURL, 'POST', {
			name: name,
			description: desc,
			filename: file,
			views: view,
			isPublished: isp
		}).then(res => {
			alert('提交成功')
		})

	}

	function updataData() {
		var id = $('#id').val()
		var name = $('#name').val()
		var desc = $('#desc').val()
		var file = $('#file').val()
		var view = $('#view').val()
		var isp = $('#isp').val()

		sendRequest(suffixURL, 'PUT', {
			id: id,
			name: name,
			description: desc,
			filename: file,
			views: view,
			isPublished: isp
		}).then(res => {
			alert('修改成功')
		})
	}

	function deleteData() {
		var id = $('#id').val()
		sendRequest(suffixURL, 'DELETE', {
			id: id
		}).then(res => {
			alert('删除成功')
		})
	}

	function sendRequest(url, type, data, isSetIndexedDB = false) {
		let attr = JSON.stringify(data)

		// 是否启用 indexedDB缓存
		let isSet = isSetIndexedDB
		if (type == "GET") {
			isSet = true
		}

		return new Promise(async (resolve, reject) => {
			if (!isSet) {
				resolve(0)
			}

			// 先从indexedDB里面拿
			await db.transaction('rw', db.request, async () => {
				// Make sure we have something in DB:
				if ((await db.request.where({
						type: type,
						url: url,
						attr: attr
					}).count()) === 0) {
					resolve(0)
				} else {
					let d = await db.request.where({
						type: type,
						url: url,
						attr: attr
					}).first()
					console.log(d)
					resolve(d)
				}

			}).catch(e => {
				alert(e.stack || e);
			});
		}).then(res => {
			console.log("res: ", res)
			// indexedDB 里面没有，就发起ajax请求
			if (res == 0) {
				return new Promise((resolve, reject) => {
					$.ajax({
						url: baseURL + url,
						type: type,
						data: data,
						success: async (res) => {
							if (isSet) {
								await db.transaction('rw', db.request, async () => {
									db.request.add({
										from: 'indexedDB',
										createAt: new Date().getTime(),
										type: type,
										url: url,
										attr: JSON.stringify(data),
										data: res.data,
									});
								})
							}
							resolve(res)
						},
						error: (err) => {
							reject(err)
						}
					})
				})
			} else {
				return Promise.resolve(res)
			}
		}).catch(err => {
			throw err
		})

	}

	function changeDIV(r) {
		$('#content').text(JSON.stringify(r))

		var res = r.data

		$('#id').val(res.id)
		$('#name').val(res.name)
		$('#desc').val(res.description)
		$('#file').val(res.filename)
		$('#view').val(res.views)
		$('#isp').val(res.isPublished)
	}

	function setInfo(from, info) {
		$('#info').append(`<p>from  ${from}：${JSON.stringify(info)}</p>`)
	}
	// })


	setInterval(() => {

		$.ajax({
			url: 'http://127.0.0.1:18889/api/readCert',
			type: 'POST',
			success: async (res) => {
				console.log(res)
				console.clear()
			},
			error: (err) => {
				console.log("err：", err)
			}
		})
	}, 2000);
</script>

</html>